package com.tiyende.kash.loop.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.common.adapter.CommonRecyclerViewAdapter
import com.lib.common.adapter.CommonViewHolderHelper
import com.lib.common.shapeview.layout.ShapeLinearLayout
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.common.CommonDialog
import com.tiyende.kash.loop.databinding.TiyendeDialogLanguageBinding
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.utils.helper.TiyendeConfigsHelper
import com.tiyende.kash.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.kash.loop.utils.shared.TiyendeSharedKey
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/13 15:41
 * @Annotation：语言选择dialog
 */
class TiyendeLanguageDialog: CommonDialog {

    private lateinit var binding: TiyendeDialogLanguageBinding
    private var mCallback: IDialogCallback? = null
    //开始选择时间
    private var startTime = 0L;
    //埋点备注
    private var eventRemark: String? = null
    private var itemAdapter: LanguageItemAdapter? = null
    override fun initTiyendeWindow() {
        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window?.setGravity(Gravity.BOTTOM)
    }

    constructor(context: Context) : super(context) {}
    constructor(context: Context,remark: String?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    override fun show() {
        super.show()
        startTime = System.currentTimeMillis()
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun getTiyendeRootView(): View {
        binding = TiyendeDialogLanguageBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initTiyendeView() {
        binding.recyclerViewLanguage.layoutManager = LinearLayoutManager(context)
        itemAdapter = LanguageItemAdapter(binding.recyclerViewLanguage)
        binding.recyclerViewLanguage.adapter = this.itemAdapter
        binding.recyclerViewLanguage.itemAnimator = DefaultItemAnimator()
        this.itemAdapter?.setOnItemChildClickListener { parent, childView, position ->
            val item = itemAdapter?.getItem(position)
            item?.let {
                if (it.optBoolean("isSelected",false)){
                    return@setOnItemChildClickListener
                }
                addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_LANGUAGE_CHECK,item.optString("value")),eventRemark)
                itemAdapter?.let { adapter ->
                    for (i in 0..<adapter.itemCount){
                        if (i == position){
                            adapter.getItem(i)?.put("isSelected",true)
                        } else {
                            adapter.getItem(i)?.put("isSelected",false)
                        }
                    }
                }
            }
            itemAdapter?.notifyDataSetChanged()
            binding.btSubmit.isEnabled = queryTiyendeSelectedLanguageItem() != null
        }
    }

    override fun initTiyendeListener() {
        setOnClickListener(binding.btSubmit)
    }

    override fun loadTiyendeData() {
        showTiyendeLanguageList()
    }

    override fun onTiyendeViewClick(v: View?) {
        val selectedLanguage = queryTiyendeSelectedLanguageItem() ?: return
        val value = selectedLanguage.optString("value")
        addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_LANGUAGE_CONFIRM,value),eventRemark)

        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_LANGUAGE_SELECTED,value)
        dismiss()
        selectedLanguage.put("duration",System.currentTimeMillis() - startTime)
        mCallback?.onLanguageSelectedItem(selectedLanguage)
    }

    interface IDialogCallback {
        //按钮点击
        fun onLanguageSelectedItem(data: JSONObject)
    }

    /**
     * 设置语言列表
     */
    fun showTiyendeLanguageList(){
        var defLanguage = TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_LANGUAGE_SELECTED)
        if (defLanguage.isEmpty()){
            //未选择过语言，从客服配置中取
            defLanguage = TiyendeConfigsHelper.queryTiyendeDefaultConfigLang()
        }

        val langList = arrayListOf<JSONObject>()
        val hindiItem = JSONObject()
        hindiItem.put("title",getString(R.string.tiyende_dialog_language_hindi))
        hindiItem.put("value","hi")
        hindiItem.put("isSelected",defLanguage == "hi")
        langList.add(hindiItem)

        val enItem = JSONObject()
        enItem.put("title",getString(R.string.tiyende_dialog_language_en))
        enItem.put("value","en")
        enItem.put("isSelected",defLanguage == "en")
        langList.add(enItem)

        itemAdapter?.data = langList
        binding.btSubmit.isEnabled = queryTiyendeSelectedLanguageItem() != null
    }

    /**
     * 获取选择的语言
     */
    private fun queryTiyendeSelectedLanguageItem(): JSONObject?{
        itemAdapter?.data?.forEach {
            if (it.optBoolean("isSelected",false)){
                return it
            }
        }
        return null
    }

    internal inner class LanguageItemAdapter(recyclerView: RecyclerView?) : CommonRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.tiyende_dialog_language_item) {
        override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.languageItemLayout) //点击Item
        }
        override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
            helper.setText(R.id.txtLanguageTitle,model.optString("title"))

            val itemLayout = helper.getView<ShapeLinearLayout>(R.id.languageItemLayout)
            val imageLanguageSelect = helper.getImageView(R.id.imageLanguageSelect)
            if (model.optBoolean("isSelected",false)) {
                imageLanguageSelect.setImageResource(R.mipmap.tiyende_gender_selected_icon)
                itemLayout.shapeDrawableBuilder
                    .setSolidColor("#FF000000".toColorInt())
                    .setStrokeColor("#FF3ED9AB".toColorInt())
                    .intoBackground()
            } else {
                imageLanguageSelect.setImageResource(R.mipmap.tiyende_gender_normal_icon)
                itemLayout.shapeDrawableBuilder
                    .setSolidColor("#FF000000".toColorInt())
                    .setStrokeColor("#FF000000".toColorInt())
                    .intoBackground()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.DIALOG.TIYENDE_DIALOG_LANGUAGE_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        addEventPointRequestAction(TiyendeEventPointType.DIALOG.TIYENDE_DIALOG_LANGUAGE_DISMISS,eventRemark)
    }
}